package com.props.starter;

import com.props.starter.config.PropsManagementProperties;
import com.props.starter.controller.PropsManagementController;
import com.props.starter.service.ConfigFileService;
import com.props.starter.service.VersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@AutoConfiguration
@EnableConfigurationProperties(PropsManagementProperties.class)
@ConditionalOnProperty(prefix = "props.management", name = "enabled", havingValue = "true", matchIfMissing = true)
@ComponentScan(basePackages = "com.props.starter")
@Slf4j
public class PropsManagementAutoConfiguration implements WebMvcConfigurer {

    private final PropsManagementProperties properties;

    public PropsManagementAutoConfiguration(PropsManagementProperties properties) {
        this.properties = properties;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 动态配置静态资源路径映射
        String managementPath = properties.getManagementPath();
        if (!managementPath.startsWith("/")) {
            managementPath = "/" + managementPath;
        }
        if (!managementPath.endsWith("/")) {
            managementPath = managementPath + "/";
        }

        log.info("✅ Props Management Static Resource Path: {}", managementPath);
        registry.addResourceHandler(managementPath + "**")
                .addResourceLocations("classpath:/static/props-management/")
                .setCachePeriod(0); // 开发时禁用缓存
    }

    @Bean
    public VersionService versionService(PropsManagementProperties properties) {
        return new VersionService(properties);
    }

    @Bean
    public ConfigFileService configFileService(PropsManagementProperties properties, @Lazy VersionService versionService) {
        return new ConfigFileService(properties, versionService);
    }

    @Bean
    public PropsManagementController propsManagementController(
            ConfigFileService configFileService,
            VersionService versionService,
            PropsManagementProperties properties) {
        return new PropsManagementController(configFileService, versionService, properties);
    }
} 